package me.helllp.book.concurrent.ch05;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable{
	private volatile boolean isRunning = true;
	
	//	内存缓冲区
	private BlockingQueue<PCData> queue;
	
	private static AtomicInteger count = new AtomicInteger();
	private static final int SLEEPTIME = 1000;
	
	public Producer(BlockingQueue<PCData> queue) {
		this.queue = queue;
	}
	
	@Override
	public void run() {
		PCData data = null;
		Random r = new Random();
		
		System.out.println("生成者开始，id=" + Thread.currentThread().getId());
		
		try {
			while(isRunning){
				Thread.sleep(r.nextInt(SLEEPTIME));
				//	构造任务数据
				data = new PCData(count.incrementAndGet());
				System.out.println(data + " 被放入Queue中");
				
				if(!queue.offer(data, 2 , TimeUnit.SECONDS)){
					System.err.println("想Queue中放数据失败 data=" + data );
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		}
	}
	
	public void stop(){
		isRunning = false;
	}
}
